package com.link.base.base.product.controller;

import com.link.base.base.product.model.Product;
import com.link.base.base.product.service.ProductService;
import com.link.base.core.apiutils.ApiBeanUtils;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.service.KeyGenerateService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/12 17:17
 * @version 1.0
 */

@Controller
public class ApiProductController {


    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private ProductService productService;

    @RequestMapping(value = "/link/api/interface/upsert",
            consumes = "application/*",
            method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsert(
            @RequestBody Product model, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            Product product = check(model);
            if (product == null) {
                product = new Product();
                Long id = keyGenerateService.keyGenerate();
                ApiBeanUtils.copyProperties(model, product);
                product.setId(id);
                product.setSource("SIEBEL");
                productService.insert(product);
            } else {
                ApiBeanUtils.copyProperties(model, product);
                product.setAnonymousFlag("Y");
                productService.update(product);
            }
            result.put("success", true);
            result.put("crmId", product.getId());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/link/api/interface/batchUpsert",
            consumes = "application/*",
            method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> batchUpsert(@RequestBody List<Product> list,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        List<Map<String, Object>> listMap = new ArrayList<>(list.size());
        try {
            for (int i = 0; i < list.size(); i++) {
                Product model = list.get(i);
                Map<String, Object> map = upsert(model, request, response);
                listMap.add(map);
            }
            result.put("success", true);
            result.put("list", list);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>检查该记录是否已存在，是则返回对象，否则返回null</p>
     * @author yrf
     * @param model
     * @return
     * @throws Exception
     */
    private Product check(Product model) throws Exception {
        Long id = model.getCrmId();
        String integrationId = model.getIntegrationId();
        if (StringUtils.isBlank(integrationId)) {
            throw new Exception("集成Id不能为空");
        }
        Product product = null;
        if (id == null) {
            //crmId 为空则根据集成Id查询
            Product example = new Product();
            example.setIntegrationId(integrationId);
            example.setPageFlag(false);
            List<Product> list = productService.queryByExamplePage(example);
            if (list != null && list.size() > 0) {
                if (list.size() == 1) {
                    product = list.get(0);
                } else {
                    throw new Exception("集成Id无法唯一确定一条记录");
                }
            }
        } else {
            Product example = new Product();
            example.setId(id);
            product = productService.queryById(example);
            if (product == null) {
                throw new Exception("crmId【" + id + "】无法获取产品信息");
            } else if (!integrationId.equals(product.getIntegrationId())) {
                throw new Exception("集成Id不匹配");
            }
        }
        return product;
    }


}
